[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. import React, { useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import {
  4. isClient, isIPageInfoForEntity, pagePathUtils, pathUtils,
  5. } from '@growi/core';
  6. import type {
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUser, IUserHasId,
  8. } from '@growi/core';
  9. import ExtensibleCustomError from 'extensible-custom-error';
  10. import {
  11. NextPage, GetServerSideProps, GetServerSidePropsContext,
  12. } from 'next';
  13. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  14. import dynamic from 'next/dynamic';
  15. import Head from 'next/head';
  16. import { useRouter } from 'next/router';
  17. import superjson from 'superjson';
  18. import { Comments } from '~/components/Comments';
  19. import { PageAlerts } from '~/components/PageAlert/PageAlerts';
  20. // import { useTranslation } from '~/i18n';
  21. import { CurrentPageContentFooter } from '~/components/PageContentFooter';
  22. import { UsersHomePageFooterProps } from '~/components/UsersHomePageFooter';
  23. import type { CrowiRequest } from '~/interfaces/crowi-request';
  24. // import { renderScriptTagByName, renderHighlightJsStyleTag } from '~/service/cdn-resources-loader';
  25. // import { useRendererSettings } from '~/stores/renderer';
  26. // import { EditorMode, useEditorMode, useIsMobile } from '~/stores/ui';
  27. import type { EditorConfig } from '~/interfaces/editor-settings';
  28. import type { CustomWindow } from '~/interfaces/global';
  29. import type { RendererConfig } from '~/interfaces/services/renderer';
  30. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  31. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  32. import type { PageModel, PageDocument } from '~/server/models/page';
  33. import type { PageRedirectModel } from '~/server/models/page-redirect';
  34. import type { UserUISettingsModel } from '~/server/models/user-ui-settings';
  35. import { useSWRxCurrentPage, useSWRxIsGrantNormalized, useSWRxPageInfo } from '~/stores/page';
  36. import { useRedirectFrom } from '~/stores/page-redirect';
  37. import {
  38. EditorMode,
  39. useEditorMode, useSelectedGrant,
  40. usePreferDrawerModeByUser, usePreferDrawerModeOnEditByUser, useSidebarCollapsed, useCurrentSidebarContents, useCurrentProductNavWidth,
  41. } from '~/stores/ui';
  42. import loggerFactory from '~/utils/logger';
  43. // import { isUserPage, isTrashPage, isSharedPage } from '~/utils/path-utils';
  44. // import GrowiSubNavigation from '../client/js/components/Navbar/GrowiSubNavigation';
  45. // import GrowiSubNavigationSwitcher from '../client/js/components/Navbar/GrowiSubNavigationSwitcher';
  46. import { DescendantsPageListModal } from '../components/DescendantsPageListModal';
  47. import { BasicLayout } from '../components/Layout/BasicLayout';
  48. import GrowiContextualSubNavigation from '../components/Navbar/GrowiContextualSubNavigation';
  49. import DisplaySwitcher from '../components/Page/DisplaySwitcher';
  50. // import { serializeUserSecurely } from '../server/models/serializers/user-serializer';
  51. // import PageStatusAlert from '../client/js/components/PageStatusAlert';
  52. import {
  53. useCurrentUser,
  54. useIsLatestRevision, useCurrentRevisionId,
  55. useIsForbidden, useIsNotFound, useIsSharedUser,
  56. useIsEnabledStaleNotification, useIsIdenticalPath,
  57. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  58. useDrawioUri, useHackmdUri, useDefaultIndentSize, useIsIndentSizeForced,
  59. useIsAclEnabled, useIsSearchPage, useTemplateTagData,
  60. useCsrfToken, useIsSearchScopeChildrenAsDefault, useCurrentPageId, useCurrentPathname,
  61. useIsSlackConfigured, useRendererConfig, useEditingMarkdown,
  62. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useCustomizedLogoSrc, useIsContainerFluid,
  63. } from '../stores/context';
  64. import {
  65. CommonProps, getNextI18NextConfig, getServerSideCommonProps, useCustomTitle,
  66. } from './utils/commons';
  67. // import { useCurrentPageSWR } from '../stores/page';
  68. const NotCreatablePage = dynamic(() => import('../components/NotCreatablePage').then(mod => mod.NotCreatablePage), { ssr: false });
  69. const ForbiddenPage = dynamic(() => import('../components/ForbiddenPage'), { ssr: false });
  70. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  71. const GrowiSubNavigationSwitcher = dynamic(() => import('../components/Navbar/GrowiSubNavigationSwitcher'), { ssr: false });
  72. const UsersHomePageFooter = dynamic<UsersHomePageFooterProps>(() => import('../components/UsersHomePageFooter')
  73. .then(mod => mod.UsersHomePageFooter), { ssr: false });
  74. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  75. const logger = loggerFactory('growi:pages:all');
  76. const {
  77. isPermalink: _isPermalink, isUsersHomePage, isTrashPage: _isTrashPage, isUserPage, isCreatablePage, isTopPage,
  78. } = pagePathUtils;
  79. const { removeHeadingSlash } = pathUtils;
  80. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  81. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  82. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  83. {
  84. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  85. return v?.data != null
  86. && v?.data.toObject != null
  87. && v?.meta != null
  88. && isIPageInfoForEntity(v.meta);
  89. },
  90. serialize: (v) => {
  91. return {
  92. data: superjson.stringify(v.data.toObject()),
  93. meta: superjson.stringify(v.meta),
  94. };
  95. },
  96. deserialize: (v) => {
  97. return {
  98. data: superjson.parse(v.data),
  99. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  100. };
  101. },
  102. },
  103. 'IPageToShowRevisionWithMetaTransformer',
  104. );
  105. const IdenticalPathPage = (): JSX.Element => {
  106. const IdenticalPathPage = dynamic(() => import('../components/IdenticalPathPage').then(mod => mod.IdenticalPathPage), { ssr: false });
  107. return <IdenticalPathPage />;
  108. };
  109. const PutbackPageModal = (): JSX.Element => {
  110. const PutbackPageModal = dynamic(() => import('../components/PutbackPageModal'), { ssr: false });
  111. return <PutbackPageModal />;
  112. };
  113. type Props = CommonProps & {
  114. currentUser: IUser,
  115. pageWithMeta: IPageToShowRevisionWithMeta | null,
  116. // pageUser?: any,
  117. redirectFrom?: string;
  118. // shareLinkId?: string;
  119. isLatestRevision?: boolean,
  120. currentRevisionId?: string,
  121. isIdenticalPathPage?: boolean,
  122. isForbidden: boolean,
  123. isNotFound: boolean,
  124. isNotCreatablePage: boolean,
  125. // isAbleToDeleteCompletely: boolean,
  126. templateTagData?: string[],
  127. isSearchServiceConfigured: boolean,
  128. isSearchServiceReachable: boolean,
  129. isSearchScopeChildrenAsDefault: boolean,
  130. isSlackConfigured: boolean,
  131. // isMailerSetup: boolean,
  132. isAclEnabled: boolean,
  133. // hasSlackConfig: boolean,
  134. drawioUri: string,
  135. hackmdUri: string,
  136. noCdn: string,
  137. // highlightJsStyle: string,
  138. isAllReplyShown: boolean,
  139. isContainerFluid: boolean,
  140. editorConfig: EditorConfig,
  141. isEnabledStaleNotification: boolean,
  142. // isEnabledLinebreaks: boolean,
  143. // isEnabledLinebreaksInComments: boolean,
  144. adminPreferredIndentSize: number,
  145. isIndentSizeForced: boolean,
  146. disableLinkSharing: boolean,
  147. rendererConfig: RendererConfig,
  148. // UI
  149. userUISettings?: IUserUISettings
  150. // Sidebar
  151. sidebarConfig: ISidebarConfig,
  152. };
  153. const GrowiPage: NextPage<Props> = (props: Props) => {
  154. // const { t } = useTranslation();
  155. const router = useRouter();
  156. const { data: currentUser } = useCurrentUser(props.currentUser ?? null);
  157. // register global EventEmitter
  158. if (isClient()) {
  159. (window as CustomWindow).globalEmitter = new EventEmitter();
  160. }
  161. // commons
  162. useEditorConfig(props.editorConfig);
  163. useCsrfToken(props.csrfToken);
  164. useCustomizedLogoSrc(props.customizedLogoSrc);
  165. // UserUISettings
  166. usePreferDrawerModeByUser(props.userUISettings?.preferDrawerModeByUser ?? props.sidebarConfig.isSidebarDrawerMode);
  167. usePreferDrawerModeOnEditByUser(props.userUISettings?.preferDrawerModeOnEditByUser);
  168. useSidebarCollapsed(props.userUISettings?.isSidebarCollapsed ?? props.sidebarConfig.isSidebarClosedAtDockMode);
  169. useCurrentSidebarContents(props.userUISettings?.currentSidebarContents);
  170. useCurrentProductNavWidth(props.userUISettings?.currentProductNavWidth);
  171. // page
  172. useIsLatestRevision(props.isLatestRevision);
  173. useIsContainerFluid(props.isContainerFluid);
  174. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  175. useIsForbidden(props.isForbidden);
  176. useIsNotFound(props.isNotFound);
  177. // useIsNotCreatable(props.IsNotCreatable);
  178. useRedirectFrom(props.redirectFrom);
  179. // useShared();
  180. // useShareLinkId(props.shareLinkId);
  181. useIsSharedUser(false); // this page cann't be routed for '/share'
  182. useIsIdenticalPath(false); // TODO: need to initialize from props
  183. // useIsAbleToDeleteCompletely(props.isAbleToDeleteCompletely);
  184. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  185. useIsSearchPage(false);
  186. useTemplateTagData(props.templateTagData);
  187. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  188. useIsSearchServiceReachable(props.isSearchServiceReachable);
  189. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  190. useIsSlackConfigured(props.isSlackConfigured);
  191. // useIsMailerSetup(props.isMailerSetup);
  192. useIsAclEnabled(props.isAclEnabled);
  193. // useHasSlackConfig(props.hasSlackConfig);
  194. useDrawioUri(props.drawioUri);
  195. useHackmdUri(props.hackmdUri);
  196. // useNoCdn(props.noCdn);
  197. useDefaultIndentSize(props.adminPreferredIndentSize);
  198. useIsIndentSizeForced(props.isIndentSizeForced);
  199. useDisableLinkSharing(props.disableLinkSharing);
  200. useRendererConfig(props.rendererConfig);
  201. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  202. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  203. useIsAllReplyShown(props.isAllReplyShown);
  204. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  205. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  206. const { pageWithMeta, userUISettings } = props;
  207. const pageId = pageWithMeta?.data._id;
  208. const pagePath = pageWithMeta?.data.path ?? (!_isPermalink(props.currentPathname) ? props.currentPathname : undefined);
  209. useCurrentPageId(pageId ?? null);
  210. // useIsNotCreatable(props.isForbidden || !isCreatablePage(pagePath)); // TODO: need to include props.isIdentical
  211. useCurrentPathname(props.currentPathname);
  212. useCurrentRevisionId(props.currentRevisionId);
  213. const { data: currentPage } = useSWRxCurrentPage(undefined, pageWithMeta?.data ?? null); // store initial data
  214. useEditingMarkdown(pageWithMeta?.data.revision?.body ?? '');
  215. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  216. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  217. const { getClassNamesByEditorMode } = useEditorMode();
  218. const shouldRenderPutbackPageModal = pageWithMeta != null
  219. ? _isTrashPage(pageWithMeta.data.path)
  220. : false;
  221. // sync grant data
  222. useEffect(() => {
  223. mutateSelectedGrant(grantData?.grantData.currentPageGrant);
  224. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant]);
  225. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  226. useEffect(() => {
  227. const decodedURI = decodeURI(window.location.pathname);
  228. if (isClient() && decodedURI !== props.currentPathname) {
  229. router.replace(props.currentPathname, undefined, { shallow: true });
  230. }
  231. }, [props.currentPathname, router]);
  232. const classNames: string[] = [];
  233. const isSidebar = pagePath === '/Sidebar';
  234. classNames.push(...getClassNamesByEditorMode(isSidebar));
  235. const isTopPagePath = isTopPage(pageWithMeta?.data.path ?? '');
  236. const isContainerFluidEachPage = currentPage == null || !('expandContentWidth' in currentPage)
  237. ? null
  238. : currentPage.expandContentWidth;
  239. const isContainerFluidDefault = props.isContainerFluid;
  240. const isContainerFluid = isContainerFluidEachPage ?? isContainerFluidDefault;
  241. return (
  242. <>
  243. <Head>
  244. {/*
  245. {renderScriptTagByName('drawio-viewer')}
  246. {renderScriptTagByName('highlight-addons')}
  247. {renderHighlightJsStyleTag(props.highlightJsStyle)}
  248. */}
  249. </Head>
  250. <BasicLayout title={useCustomTitle(props, 'GROWI')} className={classNames.join(' ')} expandContainer={isContainerFluid}>
  251. <div className="h-100 d-flex flex-column justify-content-between">
  252. <header className="py-0 position-relative">
  253. <div id="grw-subnav-container">
  254. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  255. </div>
  256. </header>
  257. <div className="d-edit-none">
  258. <GrowiSubNavigationSwitcher />
  259. </div>
  260. <div id="grw-subnav-sticky-trigger" className="sticky-top"></div>
  261. <div id="grw-fav-sticky-trigger" className="sticky-top"></div>
  262. <div className="flex-grow-1">
  263. <div id="main" className={`main ${isUsersHomePage(props.currentPathname) && 'user-page'}`}>
  264. <div id="content-main" className="content-main grw-container-convertible">
  265. { props.isIdenticalPathPage && <IdenticalPathPage /> }
  266. { !props.isIdenticalPathPage && (
  267. <>
  268. <PageAlerts />
  269. { props.isForbidden && <ForbiddenPage /> }
  270. { props.isNotCreatablePage && <NotCreatablePage />}
  271. { !props.isForbidden && !props.isNotCreatablePage && <DisplaySwitcher />}
  272. {/* <DisplaySwitcher /> */}
  273. {/* <PageStatusAlert /> */}
  274. </>
  275. ) }
  276. {/* <div className="col-xl-2 col-lg-3 d-none d-lg-block revision-toc-container">
  277. <div id="revision-toc" className="revision-toc mt-3 sps sps--abv" data-sps-offset="123">
  278. <div id="revision-toc-content" className="revision-toc-content"></div>
  279. </div>
  280. </div> */}
  281. </div>
  282. </div>
  283. </div>
  284. { !props.isIdenticalPathPage && !props.isNotFound && (
  285. <footer className="footer d-edit-none">
  286. { pageWithMeta != null && !isTopPagePath && (<Comments pageId={pageId} revision={pageWithMeta.data.revision} />) }
  287. { pageWithMeta != null && isUsersHomePage(pageWithMeta.data.path) && (
  288. <UsersHomePageFooter creatorId={pageWithMeta.data.creator._id}/>
  289. ) }
  290. <CurrentPageContentFooter />
  291. </footer>
  292. )}
  293. <UnsavedAlertDialog />
  294. <DescendantsPageListModal />
  295. <HandsontableModal />
  296. {shouldRenderPutbackPageModal && <PutbackPageModal />}
  297. </div>
  298. </BasicLayout>
  299. </>
  300. );
  301. };
  302. function getPageIdFromPathname(currentPathname: string): string | null {
  303. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  304. }
  305. class MultiplePagesHitsError extends ExtensibleCustomError {
  306. pagePath: string;
  307. constructor(pagePath: string) {
  308. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  309. this.pagePath = pagePath;
  310. }
  311. }
  312. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  313. const { model: mongooseModel } = await import('mongoose');
  314. const req: CrowiRequest = context.req as CrowiRequest;
  315. const { crowi } = req;
  316. const { revisionId } = req.query;
  317. const Page = crowi.model('Page') as PageModel;
  318. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  319. const { pageService } = crowi;
  320. let currentPathname = props.currentPathname;
  321. const pageId = getPageIdFromPathname(currentPathname);
  322. const isPermalink = _isPermalink(currentPathname);
  323. const { user } = req;
  324. if (!isPermalink) {
  325. // check redirects
  326. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  327. if (chains != null) {
  328. // overwrite currentPathname
  329. currentPathname = chains.end.toPath;
  330. props.currentPathname = currentPathname;
  331. // set redirectFrom
  332. props.redirectFrom = chains.start.fromPath;
  333. }
  334. // check whether the specified page path hits to multiple pages
  335. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  336. if (count > 1) {
  337. throw new MultiplePagesHitsError(currentPathname);
  338. }
  339. }
  340. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  341. const page = pageWithMeta?.data as unknown as PageDocument;
  342. // add user to seen users
  343. if (page != null && user != null) {
  344. await page.seen(user);
  345. }
  346. // populate & check if the revision is latest
  347. if (page != null) {
  348. page.initLatestRevisionField(revisionId);
  349. await page.populateDataToShowRevision();
  350. props.isLatestRevision = page.isLatestRevision();
  351. }
  352. if (typeof revisionId === 'string' || typeof revisionId === 'undefined') {
  353. props.currentRevisionId = props.isLatestRevision && page.latestRevision != null ? page.latestRevision.toString() : revisionId;
  354. }
  355. if (page == null && user != null) {
  356. const template = await Page.findTemplate(props.currentPathname);
  357. if (template != null) {
  358. props.templateTagData = template.templateTags as string[];
  359. }
  360. }
  361. props.pageWithMeta = pageWithMeta;
  362. }
  363. async function injectUserUISettings(context: GetServerSidePropsContext, props: Props): Promise<void> {
  364. const { model: mongooseModel } = await import('mongoose');
  365. const req = context.req as CrowiRequest<IUserHasId & any>;
  366. const { user } = req;
  367. const UserUISettings = mongooseModel('UserUISettings') as UserUISettingsModel;
  368. const userUISettings = user == null ? null : await UserUISettings.findOne({ user: user._id }).exec();
  369. if (userUISettings != null) {
  370. props.userUISettings = userUISettings.toObject();
  371. }
  372. }
  373. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  374. const req: CrowiRequest = context.req as CrowiRequest;
  375. const { crowi } = req;
  376. const Page = crowi.model('Page') as PageModel;
  377. const { currentPathname } = props;
  378. const pageId = getPageIdFromPathname(currentPathname);
  379. const isPermalink = _isPermalink(currentPathname);
  380. const page = props.pageWithMeta?.data;
  381. if (props.isIdenticalPathPage) {
  382. // TBD
  383. }
  384. else if (page == null) {
  385. props.isNotFound = true;
  386. props.isNotCreatablePage = !isCreatablePage(currentPathname);
  387. // check the page is forbidden or just does not exist.
  388. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  389. props.isForbidden = count > 0;
  390. }
  391. else {
  392. props.isNotFound = page.isEmpty;
  393. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  394. if (isPermalink && page.isEmpty) {
  395. props.currentPathname = page.path;
  396. }
  397. // /path/to/page ==> /62a88db47fed8b2d94f30000
  398. if (!isPermalink && !page.isEmpty) {
  399. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  400. if (!isToppage) {
  401. props.currentPathname = `/${page._id}`;
  402. }
  403. }
  404. }
  405. }
  406. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  407. // const req: CrowiRequest = context.req as CrowiRequest;
  408. // const { crowi } = req;
  409. // const UserModel = crowi.model('User');
  410. // if (isUserPage(props.currentPagePath)) {
  411. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  412. // if (user != null) {
  413. // props.pageUser = JSON.stringify(user.toObject());
  414. // }
  415. // }
  416. // }
  417. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  418. const req: CrowiRequest = context.req as CrowiRequest;
  419. const { crowi } = req;
  420. const {
  421. appService, searchService, configManager, aclService, slackNotificationService, mailService,
  422. } = crowi;
  423. props.isSearchServiceConfigured = searchService.isConfigured;
  424. props.isSearchServiceReachable = searchService.isReachable;
  425. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  426. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  427. // props.isMailerSetup = mailService.isMailerSetup;
  428. props.isAclEnabled = aclService.isAclEnabled();
  429. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  430. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  431. props.hackmdUri = configManager.getConfig('crowi', 'app:hackmdUri');
  432. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  433. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  434. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  435. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  436. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  437. // props.isEnabledLinebreaks = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks');
  438. // props.isEnabledLinebreaksInComments = configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments');
  439. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  440. props.editorConfig = {
  441. upload: {
  442. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  443. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  444. },
  445. };
  446. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  447. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  448. props.rendererConfig = {
  449. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  450. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  451. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  452. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  453. plantumlUri: process.env.PLANTUML_URI ?? null,
  454. blockdiagUri: process.env.BLOCKDIAG_URI ?? null,
  455. // XSS Options
  456. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:xss:isEnabledPrevention'),
  457. attrWhiteList: crowi.xssService.getAttrWhiteList(),
  458. tagWhiteList: crowi.xssService.getTagWhiteList(),
  459. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  460. };
  461. props.sidebarConfig = {
  462. isSidebarDrawerMode: configManager.getConfig('crowi', 'customize:isSidebarDrawerMode'),
  463. isSidebarClosedAtDockMode: configManager.getConfig('crowi', 'customize:isSidebarClosedAtDockMode'),
  464. };
  465. }
  466. /**
  467. * for Server Side Translations
  468. * @param context
  469. * @param props
  470. * @param namespacesRequired
  471. */
  472. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  473. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  474. props._nextI18Next = nextI18NextConfig._nextI18Next;
  475. }
  476. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  477. const req = context.req as CrowiRequest<IUserHasId & any>;
  478. const { user } = req;
  479. const result = await getServerSideCommonProps(context);
  480. // check for presence
  481. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  482. if (!('props' in result)) {
  483. throw new Error('invalid getSSP result');
  484. }
  485. const props: Props = result.props as Props;
  486. if (props.redirectDestination != null) {
  487. return {
  488. redirect: {
  489. permanent: false,
  490. destination: props.redirectDestination,
  491. },
  492. };
  493. }
  494. if (user != null) {
  495. props.currentUser = user.toObject();
  496. }
  497. try {
  498. await injectPageData(context, props);
  499. }
  500. catch (err) {
  501. if (err instanceof MultiplePagesHitsError) {
  502. props.isIdenticalPathPage = true;
  503. }
  504. else {
  505. throw err;
  506. }
  507. }
  508. await injectUserUISettings(context, props);
  509. await injectRoutingInformation(context, props);
  510. injectServerConfigurations(context, props);
  511. await injectNextI18NextConfigurations(context, props, ['translation']);
  512. return {
  513. props,
  514. };
  515. };
  516. export default GrowiPage;